package com.mililoan.common.spring;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

/**
 * 
 * @ClassName: MulitViewResolver
 * @Description: 多视图分发视图
 * @author YangChaofeng 2016年4月26日 下午5:19:05
 */
public class MulitViewResolver implements ViewResolver {

	private Logger logger = Logger.getLogger(getClass());
	private Map<Set<String>, ViewResolver>	viewResolverMap		= new HashMap<Set<String>, ViewResolver>();
	private ViewResolver					defaultViewResolver	= null;

	public View resolveViewName(String viewName, Locale locale) throws Exception {
		for (Map.Entry<Set<String>, ViewResolver> map : viewResolverMap.entrySet()) {
			Set<String> suffixs = map.getKey();
			for (String suffix : suffixs) {
				if (viewName.endsWith(suffix)) {// 根据后缀分发
					ViewResolver viewResolver = map.getValue();
					if (null != viewResolver) {
						if (logger.isDebugEnabled()) {
							logger.debug("找到视图解析器: '" + viewResolver + "' 视图名称: '" + viewName + "'");
						}
						return viewResolver.resolveViewName(viewName, locale);
					}
				}
			}
		}

		if (defaultViewResolver != null) {
			return defaultViewResolver.resolveViewName(viewName, locale);
		}
		return null;
	}

	public Map<Set<String>, ViewResolver> getViewResolverMap() {
		return viewResolverMap;
	}

	public void setViewResolverMap(Map<Set<String>, ViewResolver> viewResolverMap) {
		this.viewResolverMap = viewResolverMap;
	}

	public ViewResolver getDefaultViewResolver() {
		return defaultViewResolver;
	}

	public void setDefaultViewResolver(ViewResolver defaultViewResolver) {
		this.defaultViewResolver = defaultViewResolver;
	}

}
